/* eslint-disable jsx-a11y/alt-text */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import {
  Form,
  Input,
  Button,
  Card,
  Icon,
  InputNumber,
  Radio,
  Checkbox,
  Row,
  Col,
  message,
  Modal,
  Upload,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import router from 'umi/router';
import styles from './Roomdetail.less';

const FormItem = Form.Item;
const { TextArea } = Input;

@connect(({ room, loading }) => ({
  room,
  submitting: loading.effects['root/Get'],
}))
@Form.create()
class BasicForms extends PureComponent {

  state = {
    roomTags: [
      {
        tag: { name: "网络电视", 
          icon: "https://cnd2.yeseesports.com/files/tv.png", 
          id: 1
      }
      }, 
      {
        tag: { name: "公共赛车模拟器", 
          icon: "https://cnd2.yeseesports.com/files/TORCS.png", 
          id: 2
      }
      }, 
      {
        tag: {
          name: "24小时热水", 
          icon: "https://cnd2.yeseesports.com/files/hotwater.png", 
          id: 3
        }
      }, 
      {
        tag: {
          name: "公共电竞游戏", 
          icon: "https://cnd2.yeseesports.com/files/game.png", 
          id: 4
        }
      }, 
      {
        tag: {
          name: "浴缸", 
          icon: "https://cnd2.yeseesports.com/files/tub.png", 
          id: 5
        }
      }, 
      {
        tag: {
          name: "免费WIFI", 
          icon: "https://cnd2.yeseesports.com/files/wifi.png", 
          id: 6
        }
      }, 
      {
        tag: {
          name: "公用洗衣机", 
          icon: "https://cnd2.yeseesports.com/files/fridge.png", 
          id: 7
        }
      }, 
      {
        tag: {
          name: "公共图书阅览", 
          icon: "https://cnd2.yeseesports.com/book.png", 
          id: 11
        }
      }
  ],
    
    fileList: [],
  };
  handleCancel = () => this.setState({ previewVisible: false });
  componentDidMount() {
    const root = this;
    const { dispatch, match: { params = {} } } = root.props;
    if (params.id) {
      dispatch({
        type: 'room/Get',
        payload: params,
        callback: response => {
          const roomPictures = response.result.roomPictures.map(item => ({
            uid: item.id,
            status: 'done',
            url: item.pictureUrl,
          }));
          root.setState({
            modelflag: true,
            fileList: roomPictures,
            style: { display: "block" },
            roomname: '修改房型'
          })
        }
      });
    } else {
      root.setState({
        modelflag: false,
        fileList: [],
        style: { display: "none" },
        roomname: '新建房型'
      })

    }

  }

  handleUpdateModalVisible = () => {
    router.push("/list/card-list")

  };
  handleSubmit = e => {
    const { dispatch, form } = this.props;
    const { fileList } = this.state;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const roomTags = values.roomTags.map(item => ({
          tagId: item
        }));
        const roomPictures = fileList.map(item => ({
          pictureUrl: item.url,
        }));
        if (roomPictures.length != 0) {

          if (this.state.modelflag) {
            dispatch({
              type: 'room/UpdateRoom',
              payload: {
                ...values,
                roomTags,
                roomPictures,
              },
              callback: response => {
                if (response.success) {
                  message.success("操作成功");
                  router.push("/list/card-list")
                }
              }
            });


          } else {

            dispatch({
              type: 'room/CreateRoom',
              payload: {
                ...values,
                roomTags,
                roomPictures,
              },
              callback: response => {
                if (response.success) {
                  message.success("操作成功");
                  router.push("/list/card-list")
                }
              }
            });


          }
        } else {
          message.error("请至少上传一张图片");
        }
      }
    });
  };

  onSuccess = (response, file) => {
    const { result: { httpUrl, isSuccess }, success } = response;
    const { fileList } = this.state;
    if (success && isSuccess) {
      this.setState({
        fileList: [
          ...fileList,
          {
            ...file,
            status: 'done',
            url: httpUrl,
          }
        ]
      })
    }
  };
  handleRemove = (file) => {
    for (let i = 0; i < this.state.fileList.length; i++) {
      if (file.url === this.state.fileList[i].url) {
        this.state.fileList.splice(i, 1);
      } else {

      }
    }
    this.setState({
      fileList: this.state.fileList
    })
    this.forceUpdate();

  }


  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };
  render() {
    const { submitting, room: { values = {} } } = this.props;
    const { roomTags, fileList } = this.state;
    const { previewVisible, previewImage } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    return (
      <PageHeaderWrapper
        title={<FormattedMessage id='房型详情' />}
      >
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            {getFieldDecorator('id', {
              initialValue: values.id || '',
            })(<Input type='hidden' />)}
            <FormItem {...formItemLayout} label={<FormattedMessage id="房型" />}>
              {getFieldDecorator('name', {
                initialValue: values.name || '',
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: '给房型起个名字' }),
                  },
                ],
              })(<Input placeholder={formatMessage({ id: '给房型起个名字' })} />)}
            </FormItem>
            <FormItem
              style={this.state.style}
              {...formItemLayout}
              label={<FormattedMessage id="状态"
              />}
            >
              <div>
                {getFieldDecorator('roomStatus', {
                  initialValue: `${values.roomStatus}` || '0',
                })(
                  <Radio.Group>
                    <Radio value="0">
                      <FormattedMessage id="上架" />
                    </Radio>
                    <Radio value="1">
                      <FormattedMessage id="下架" />
                    </Radio>
                  </Radio.Group>
                )}
              </div>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={<FormattedMessage id="支持包院"
              />}
            >
              <div>
                {getFieldDecorator('isPrivateRoom', {
                  initialValue: `${values.isPrivateRoom}` || '0',
                })(
                  <Radio.Group>
                    <Radio value="0">
                      <FormattedMessage id="不包院" />
                    </Radio>
                    <Radio value="1">
                      <FormattedMessage id="包院" />
                    </Radio>
                  </Radio.Group>
                )}
              </div>
            </FormItem>
            <FormItem {...formItemLayout} label={<FormattedMessage id="房型描述" />}>
              {getFieldDecorator('description', {
                initialValue: values.description || '',
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: '请输入房型简单的介绍' }),
                  },
                ],
              })(
                <TextArea
                  style={{ minHeight: 32 }}
                  placeholder={formatMessage({ id: '请输入房型简单的介绍' })}
                  rows={4}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={<FormattedMessage id="房型设施" />}>
              {getFieldDecorator('roomTags', {
                initialValue: values.roomTags.map(({ tag }) => tag.id) || [],
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: '房型设施' }),
                  },
                ],
              })(
                <Checkbox.Group style={{ width: '100%' }}>
                  <Row gutter={16} >
                    {
                      roomTags.map(({ tag }) => (
                        <Col span={6} className={styles.appc} key={tag.id}>
                          <img className={styles.roomacilities} src={tag.icon} />
                          <Checkbox value={tag.id} className={styles.roomacilitiesCheckbox}>{tag.name}</Checkbox>
                        </Col>
                      ))
                    }
                  </Row>
                </Checkbox.Group>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={
                <span>
                  <FormattedMessage id="基础价格" />
                </span>
              }
            >
              <span className="ant-form-text">(在没有特殊价格的情况下，基础价格即为销售价格)</span>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={
                <span>
                  <FormattedMessage id="平日价格" />
                </span>
              }
            >
              {getFieldDecorator('defaultPrice', {
                initialValue: values.defaultPrice,
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: '请设置平日基本价格' }),
                  },
                ],
              })(
                <InputNumber
                  placeholder={formatMessage({ id: '请设置平日基本价格' })}
                  min={0}
                />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={
                <span>
                  <FormattedMessage id="周末价格" />
                </span>
              }
            >
              {getFieldDecorator('weekendPrice', {
                initialValue: values.weekendPrice,
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: '请设置周末基本价格' }),
                  },
                ],
              })(
                <InputNumber
                  placeholder={formatMessage({ id: '请设置周末基本价格' })}
                  min={0}
                />
              )}
              <span className="ant-form-text">（周末指周五与周六）</span>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={
                <span>
                  <FormattedMessage id="房型图片" />
                </span>
              }
            >
              <Upload
                action="https://seventh.chinacloudsites.cn/api/services/app/Weixin/UploadFile"
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
                onSuccess={this.onSuccess}
                onRemove={this.handleRemove}
              >
                {fileList.length >= 9 ? null : uploadButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                修改
                  </Button>
              <a onClick={() => this.handleUpdateModalVisible()}>
                <Button style={{ marginLeft: 8 }} >
                  取消
                  </Button>
              </a>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderWrapper>
    );

  }

}

export default BasicForms;
